/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import React, { Component, Fragment } from 'react';
import { Button, Intent } from '@blueprintjs/core';
import { Descriptions } from 'antd';

// Services
import { LicenseService } from '../../../../../services';

// UI
import { ErrorMessage, ExternalLink, Loading } from '../../../../UI';

// Dialogs
import { EnterLicenseDialog } from '../../../../Dialogs';

// Utils
import { Links } from '../../../../../utils';

// Components
const { Item } = Descriptions;

// Constants
const ITEM_SPAN = 3;
const ERROR_MSG = 'Error fetching data from license';

class PanelLicenseManagement extends Component {
  _isMounted = false;

  state = {
    license: {},
    isOpenEnterLicenseDialog: false,
    loading: true,
    error: false,
    errorMsg: ERROR_MSG
  };

  componentDidMount() {
    this._isMounted = true;
    this.callApiGetLicense();
  }

  componentWillUnmount() {
    this._isMounted = false;
    LicenseService.cancelRequest();
  }

  callApiGetLicense = () => {
    this.setState({
      loading: true,
      error: false
    });

    LicenseService.getLicense()
      .then(res => {
        if (this._isMounted && res.status === 200) {
          const { data } = res;

          this.setState({
            license: data,
            loading: false
          });
        } else {
          if (this._isMounted) {
            this.setState({
              loading: false,
              error: true
            });
          }
        }
      })
      .catch(error => {
        if (this._isMounted) {
          this.setState({
            loading: false,
            error: true
          });
        }
      });
  };

  handleEnterLicenseDialog = () => {
    this.setState(prevState => ({
      isOpenEnterLicenseDialog: !prevState.isOpenEnterLicenseDialog
    }));
  };

  renderDescriptions() {
    const { license, isOpenEnterLicenseDialog } = this.state;

    return (
      <Fragment>
        <div className="sku-btn-group-end m-b-10">
          <ExternalLink
            href={Links.saiku.license}
            className="bp3-button bp3-icon-dollar bp3-intent-success bp3-small m-r-5"
          >
            Purchase License
          </ExternalLink>
          <Button
            icon="key"
            text="Enter License"
            intent={Intent.DANGER}
            onClick={this.handleEnterLicenseDialog}
            small
          />
        </div>
        <Descriptions bordered size="small">
          <Item label="License Type" span={ITEM_SPAN}>
            {license.licenseType}
          </Item>
          <Item label="License Number" span={ITEM_SPAN}>
            {license.licenseNumber}
          </Item>
          <Item label="Name" span={ITEM_SPAN}>
            {license.name}
          </Item>
          <Item label="Company" span={ITEM_SPAN}>
            {license.company}
          </Item>
          <Item label="User Limit" span={ITEM_SPAN}>
            {license.userLimit}
          </Item>
          <Item label="License Expiry" span={ITEM_SPAN}>
            {license.expiration}
          </Item>
        </Descriptions>

        {isOpenEnterLicenseDialog && (
          <EnterLicenseDialog
            hideErrorContent={this.hideErrorContent}
            onClose={this.handleEnterLicenseDialog}
          />
        )}
      </Fragment>
    );
  }

  render() {
    const { loading, error, errorMsg } = this.state;

    return loading ? (
      <Loading className="m-t-10 m-b-10" size={30} center />
    ) : error ? (
      <ErrorMessage text={errorMsg} callApi={this.callApiGetLicense} />
    ) : (
      this.renderDescriptions()
    );
  }
}

export default PanelLicenseManagement;
